const jsonwebtoken = require('jsonwebtoken')
const {promisify} = require('util')
const pSign = promisify(jsonwebtoken.sign)
const pVerify = promisify(jsonwebtoken.verify)
const baseConfig = require('../config/config.default')
// 生成token
module.exports.createToken = async userInfo => {
    return await pSign(userInfo, baseConfig.tokenId, {
        expiresIn: baseConfig.validTime
    })
}

// 验证token
module.exports.verifyToken = async (req, res, next) => {
    let token = req.headers.authorization
    token = token ? token.split('Bearer ')[1] : null
    if (!token) {
        res.status(400).json({
            error: '请求未授权，token不存在'
        })
    }
    // token存在解密
    try {
        req.user = await pVerify(token, baseConfig.tokenId, {})
        next()
    } catch (err) {
        res.status(400).json({
            error: '无效token'
        })
    }
}
